package cn.com.cetccst.compliancecheck.demo.model;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import cn.com.cetccst.compliancecheck.ComplianceCheckManager;
import cn.com.cetccst.compliancecheck.log.ComplianceLogger;
import cn.com.cetccst.compliancecheck.checker.CheckerType;

public class MainModel extends ViewModel {
    private ComplianceCheckManager complianceCheckManager = ComplianceCheckManager.getInstance();
    private MutableLiveData<String> logMsg = new MutableLiveData<>("");
    private String logMsgStr = "";

    public MainModel() {
        complianceCheckManager.setLogger(this::log);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        complianceCheckManager.setLogger(null);
    }

    public void checkModel() {
        ComplianceLogger.log(complianceCheckManager.check(CheckerType.DeviceModel).name());
    }

    public void checkOS() {
        ComplianceLogger.log(complianceCheckManager.check(CheckerType.OSVersion).name());
    }

    public void checkApplication() {
        ComplianceLogger.log(complianceCheckManager.check(CheckerType.Application).name());
    }

    public void checkRoot() {
        complianceCheckManager.check(CheckerType.Root);
    }

    public void checkSIMCard() {
        complianceCheckManager.check(CheckerType.SIMCard);
    }

    public void checkLocation() {
        complianceCheckManager.check(CheckerType.Location);
    }

    public void checkSystemTime() {
        complianceCheckManager.check(CheckerType.SystemTime);
    }

    public void checkConnection() {
        complianceCheckManager.check(CheckerType.Connection);
    }

    public void startCheckAllPeriodically() {
        complianceCheckManager.startCheckPeriodically(20 * 1000);
    }

    public void clearLog() {
        logMsgStr = "";
        logMsg.setValue(logMsgStr);
    }

    public MutableLiveData<String> getLogMsg() {
        return logMsg;
    }

    private void log(String msg) {
        Log.d("ComplianceCheckLog", msg);
        if (msg.endsWith("\n")) {
            logMsgStr += msg;
        } else {
            logMsgStr += (msg + "\n");
        }
        logMsg.postValue(logMsgStr);
    }
}
